import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.msgpack.MessagePack;
import org.msgpack.type.Value;
import org.newbee.message.Animal;
import org.newbee.message.MessageHeader;
import org.newbee.message.User;
import org.newbee.proto.OrderProtocol;
;

/**
 * Created by iss on 17/6/2.
 */
public class NettyTestServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        Value value = (Value) msg;
//        MessagePack messagePack = new MessagePack();
//        MessageHeader messageHeader = messagePack.convert(value, MessageHeader.class);
//        if (messageHeader.getType() == 10) {
//            User user = messagePack.read(messageHeader.getContent(), User.class);
//            System.out.println(user.getName());
//        } else {
//            Animal animal = messagePack.read(messageHeader.getContent(), Animal.class);
//            System.out.println(animal.getName());
//        }
        OrderProtocol.Order order = (OrderProtocol.Order) msg;
        System.out.println(order);
        ctx.channel().writeAndFlush(order);

//        String key = msg.toString();
//        if (key.contains("keep")) {
//            key = key.replace("keep", "");
//            NettyTestUtil.pool.put(key, ctx);
//        } else {
//            Set<Map.Entry<String, ChannelHandlerContext>> set = NettyTestUtil
//                    .pool.entrySet();
//            Iterator<Map.Entry<String, ChannelHandlerContext>> itr = set.iterator();
//            while (itr.hasNext()) {
//                Map.Entry<String, ChannelHandlerContext> entry = itr.next();
//                if (key.contains(entry.getKey())) {
//                    key = key.replace(entry.getKey(), "");
//                    ChannelHandlerContext cachedContext = entry.getValue();
//                    cachedContext.channel().writeAndFlush(NettyTestUtil.encodeString(key));
//                }
//            }
//        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
